<template>
  <div
    v-loading="loading"
    style="width: 95%"
  >

    <el-row :gutter="10">
      <el-col class="main-content">
        <!-- 输入框 -->
        <el-row :gutter="10">
          <el-col :span="10">
            <el-input
              v-model="inputText"
              size="large"
              placeholder="输入内容"
              @change="handleInputChange"
            >
            </el-input>
          </el-col>
          <el-col :span="14">
            <el-alert
              :title="errorMsg"
              type="error"
              effect="dark"
              :closable="false"
              v-show="errorMsg"
            >
            </el-alert>
            <el-alert
              :title="successMsg"
              type="success"
              effect="dark"
              :closable="false"
              v-show="successMsg"
            >
            </el-alert>

          </el-col>
        </el-row>

        <!-- 内容展示 -->
        <el-row
          :gutter="10"
          class="marginTop10"
        >
          <!-- 左侧面板 -->
          <el-col :span="8">
            <!-- 采集设置 & 订单信息 -->
            <el-row>

              <el-col :span="24">
                <el-card style="width: 100%;box-sizing: border-box; ">
                  <template #header>
                    <div>
                      <span>采集信息</span>
                    </div>
                  </template>

                  <!-- 采集信息 -->
                  <div>
                    <el-row>
                      <el-col :span="24">
                        <el-form :model="orderData">
                          <el-form-item label="站点">
                            <el-select
                              v-model="orderData.wpno"
                              placeholder="选择站点"
                              style="width: 100%;"
                              filterable
                            >
                              <el-option
                                v-for="wpno in orderData.wpnoOptions"
                                :label="wpno['名称']"
                                :value="wpno['工序ID']"
                              >
                              </el-option>
                            </el-select>
                          </el-form-item>
                          <el-form-item label="操作员">
                            <div v-for="x in orderData.operator">{{x['EMPLOYEEID'] + '-' + x['EMP_NAME']}},</div>
                          </el-form-item>

                          <!-- 订单号字段 -->
                          <el-form-item
                            label="订单号："
                            prop="orderNumber"
                          >
                            <el-input
                              v-model="orderData.orderNumber"
                              clearable
                              disabled
                            >
                            </el-input>
                          </el-form-item>

                          <!-- 物料号字段 -->
                          <el-form-item
                            label="物料号："
                            prop="materialNumber"
                          >
                            <el-input
                              v-model="orderData.materialNumber"
                              clearable
                              disabled
                            >
                            </el-input>
                          </el-form-item>

                          <!-- 描述字段 -->
                          <el-form-item
                            label="描述："
                            prop="description"
                          >
                            <el-input
                              v-model="orderData.description"
                              clearable
                              disabled
                            >
                            </el-input>
                          </el-form-item>

                          <!-- 数量字段 -->
                          <el-form-item
                            label="数量："
                            prop="quantity"
                          >

                            <el-input
                              v-model="orderData.quantity"
                              clearable
                              disabled
                            >
                            </el-input>
                          </el-form-item>

                          <!-- 流水号字段 -->
                          <!-- <el-form-item
                            label="流水号："
                            prop="serialNumber"
                          >
                            <el-input
                              v-model="orderData.serialNumber"
                              clearable
                              disabled
                            ></el-input>
                          </el-form-item> -->

                          <!-- 备注字段 -->
                          <el-form-item
                            label="备注："
                            prop="remark"
                          >
                            <el-input
                              v-model="orderData.remark"
                              type="textarea"
                              :rows="3"
                              maxlength="200"
                              show-word-limit
                              disabled
                            ></el-input>
                          </el-form-item>

                        </el-form>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-table
                        border
                        stripe
                        :data="orderData.bomData"
                        height="230"
                        :row-class-name="tableRowClassName"
                      >
                        <el-table-column
                          prop="MATCODE"
                          label="物料"
                          width="120"
                          align="center"
                        ></el-table-column>
                        <el-table-column
                          prop="MATNAME"
                          label="描述"
                          align="center"
                        ></el-table-column>
                        <el-table-column
                          prop="BOMDOSAGE"
                          label="单个数量"
                          width="120"
                          align="center"
                        ></el-table-column>
                        <el-table-column
                          prop="BOMAMOUNT"
                          label="BOM总数"
                          width="120"
                          align="center"
                        ></el-table-column>
                      </el-table>
                    </el-row>
                  </div>
                </el-card>
              </el-col>
            </el-row>

          </el-col>

          <!-- 右侧面板 -->
          <el-col :span="16">
            <!-- 采集列表 -->
            <el-card style="width: 100%;box-sizing: border-box; ">
              <template #header>
                <div>
                  <span>采集列表</span>
                </div>
              </template>
              <el-row :gutter="15">
                <el-col :span="12">
                  <div class="form-row">
                    <div class="form-label">日期：</div>
                    <el-date-picker
                      v-model="orderData.collectionDate"
                      type="date"
                      placeholder="选择日期"
                      value-format="YYYY/MM/DD"
                      format="YYYY/MM/DD"
                      style="width: 100%;"
                      disabled
                    >
                    </el-date-picker>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="form-row">
                    <div class="form-label">流水号：</div>
                    <el-input
                      v-model="orderData.collectionSerial"
                      placeholder="请输入流水号"
                      disabled
                    ></el-input>
                  </div>
                </el-col>
              </el-row>
              <el-row
                :gutter="10"
                style="margin-top: 15px;"
              >
                <el-col :span="12">
                  <el-button
                    type="primary"
                    icon="el-icon-refresh"
                    style="width: 100%;"
                  >重新采集</el-button>
                </el-col>
                <el-col :span="12">
                  <el-button
                    type="success"
                    icon="el-icon-check"
                    style="width: 100%;"
                  >提交采集</el-button>
                </el-col>
                <el-col :span="8">
                  <!-- <el-button
                    icon="el-icon-refresh-right"
                    style="width: 100%;"
                  >刷新</el-button> -->
                </el-col>
              </el-row>

              <el-tabs
                v-model="orderData.activeTab"
                style="margin-top: 15px;"
              >
                <el-tab-pane
                  label="已采集"
                  name="collected"
                >
                  <el-table
                    :data="orderData.bomDataZGJ"
                    style="width: 100%"
                    height="180"
                    :row-class-name="tableRowClassName"
                    border
                    stripe
                  >
                    <el-table-column
                      prop="MATCODE"
                      label="物料"
                      align="center"
                      width="120"
                    ></el-table-column>
                    <el-table-column
                      prop="MATNAME"
                      label="描述"
                      align="center"
                      width="200"
                    ></el-table-column>
                    <el-table-column
                      prop="SUPPLIER"
                      align="center"
                      label="供应商"
                      width="200"
                    ></el-table-column>
                    <el-table-column
                      prop="PRAMATSN"
                      label="批次/流水"
                      align="center"
                    ></el-table-column>
                  </el-table>
                </el-tab-pane>
              </el-tabs>
            </el-card>

            <!-- 当前工作 -->
            <el-card style="width: 100%;box-sizing: border-box; ">
              <template #header>
                <div>
                  <span>采集记录</span>
                </div>
              </template>
              <el-table
                border
                stripe
                :data="currentWorkData"
                style="width: 100%"
                height="180"
                :row-class-name="tableRowClassName"
              >
                <el-table-column
                  prop="serial"
                  label="流水号"
                  width="200"
                ></el-table-column>
                <el-table-column
                  prop="description"
                  label="描述"
                ></el-table-column>
                <el-table-column
                  prop="result"
                  label="采集结果"
                  width="100"
                >
                  <template #default="scope">
                    <el-tag :type="scope.row.result === '成功' ? 'success' : 'danger'">
                      {{ scope.row.result }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="material"
                  label="物料号"
                  width="100"
                ></el-table-column>
                <el-table-column
                  prop="operator"
                  label="操作员"
                  width="80"
                ></el-table-column>
              </el-table>
            </el-card>

          </el-col>
        </el-row>
      </el-col>
    </el-row>

  </div>
</template>
<script>
import { computed, reactive, ref } from 'vue';
import { onMounted, watch } from '@vue/runtime-core';

import { v4 } from 'uuid';

import myAxios from '@/myAxios/myAxios';
import { showWarning } from '@/hooks/useMyMessageBox';
import store from '@/store';
import { dayjs } from 'element-plus';

export default {
  name: 'EmployeeAndDepartmentView',
  setup () {
    let loading = ref(false);
    let addBtnClick = function (EMP_CLASS) {
      let row = {
        'EMPLOYEEID': v4(),
        'EMP_CLASS': EMP_CLASS,
        'EMP_NAME': '',
        'EMP_NOTES': '',
        'EMP_DEPARTMENT': EMP_CLASS == 'E' ? tableDatas.filters.department : '',
        'EMP_TYPE': EMP_CLASS == 'E' ? 'A' : '',
        'isNew': true,
      };
      showFormDialog(row);
    };
    let deleteBtnClick = function () {
      if (tableDatas.oritableData.length) {
        showWarning('部门下仍有职员，请先删除职员');
        return;
      }
      else {
        if (tableDatas.filters.department) {
          let row = {
            'EMPLOYEEID': tableDatas.filters.department,
            'EMP_CLASS': 'D',
          };
          tableDatas.deleteBtnClick(row);
        }
      }
      // showFormDialog();
    };
    let buttonClick = {
      addBtnClick,
      deleteBtnClick,
    };

    let getWpnoOptions = async function () {
      let params = `${9900}`;

      let res = await myAxios.get('陈帅廷查询大连工序', params);
      if (res instanceof Array) {
        orderData.wpnoOptions = res;
      }
    };
    // myAxios.postToWeChatText('14602', '1111', '2222');
    let getTableDatas = async function (department) {
      loading.value = true;
      if (!department) {
        let databaseAccount = store.state.databaseAccount;
        let params = `${databaseAccount}`;

        tableDatas.oriDepartmentData = await myAxios.get('WEB_MES_获取部门信息', params);
        tableDatas.filters.department = tableDatas.oriDepartmentData[0]['EMPLOYEEID'];
      }
      else {
        tableDatas.filters.department = department;
      }
      let params = `${tableDatas.filters.department}`;
      let databaseAccount = store.state.databaseAccount;
      params += `🈹${databaseAccount}`;

      myAxios.get('WEB_MES_获取部门人员信息', params).then(res => {
        if (res instanceof Array) {
          loading.value = false;
          tableDatas.oritableData = [...res];
          // ElMessage({
          //   showClose: true,
          //   type: 'success',
          //   message: '最新数据获取成功!'
          // });
        }
        else {
          loading.value = false;
          showWarning('获取数据失败res!' + res);
        }
      }).catch((err) => {
        loading.value = false;
        showWarning('获取数据失败err!' + err);
      });
    };

    onMounted(() => {
      // getTableDatas();
      getWpnoOptions();
    });
    const inputText = ref('$EMP$');
    const handleInputChange = async function (value) {
      errorMsg.value = '';
      successMsg.value = '';
      if (value) {
        value = value.trim().toUpperCase();
        if (value.startsWith('$EMP$')) {
          let workid = value.substring(5);
          let operatorParam = `EMPLOYEE🈹EMPLOYEEID🈹${workid}`;
          let operatorInfoList = await myAxios.get('陈帅廷查询大连通用数据', operatorParam);
          if (operatorInfoList.length) {
            orderData.operator.push(...operatorInfoList);
            successMsg.value = '采集人员: ' + operatorInfoList[0]['EMP_NAME'] + ' 成功';
            inputText.value = '';
          }
          else {
            errorMsg.value = '未找到人员工号:' + workid;
          }
          // getTableDatas(value);
        }
        //$MATBATCH$A2160167$0010002543$231011-10
        //$MATSNSP$A2102429$0010000466$MD-A2102429-250617
        else if (value.startsWith('$MATBATCH$') || value.startsWith('$MATSNSP$')) {
          if (!orderData.collectionSerial) {
            errorMsg.value = '请先输入流水号';
            return;
          }
          let matList = value.split('$');
          let matcode = matList[2];
          let supplierCode = matList[3].padStart(10, '0');
          let matsn = matList[4];
          if (orderData.bomDataZGJ.length) {
            let zgjData = orderData.bomDataZGJ.find(el => el['MATCODE'] == matcode);
            if (zgjData) {
              zgjData.PRAMATSN = matsn;
              let supplierParam = `SUPPLIER🈹SUPPLIERID🈹${supplierCode}`;
              let supplierInfoList = await myAxios.get('陈帅廷查询大连通用数据', supplierParam);
              if (supplierInfoList.length) {
                zgjData.SUPPLIER = supplierInfoList[0]['SUPPNAME'];
                successMsg.value = '主关键: ' + matcode + ' 扫码成功';
                inputText.value = '';
              }
              else {
                errorMsg.value = '未找到供应商: ' + supplierCode;
              }
            }
            else {
              errorMsg.value = '未找到主关键: ' + matcode;
            }
          }
          else {
            errorMsg.value = '无需采集主关键: ' + matcode;
          }

        }
        else {
          if (!orderData.wpno) {
            errorMsg.value = '请选择站点';
            return;
          }
          if (!orderData.operator.length) {
            errorMsg.value = '请输入采集员';
            return;
          }
          value = value.trim().toUpperCase();
          let snParam = `JM_WORKORDERSN🈹PROSN🈹${value}`;
          let snInfoList = await myAxios.get('陈帅廷查询大连通用数据', snParam);
          if (snInfoList.length) {
            let JM_WORKORDERID = snInfoList[0]['JM_WORKORDERID'];
            let orderParam = `JM_WORKORDER🈹JM_WORKORDERID🈹${JM_WORKORDERID}`;
            let orderInfoList = await myAxios.get('陈帅廷查询大连通用数据', orderParam);
            if (orderInfoList.length) {
              let orderEntity = orderInfoList[0];
              orderData.orderNumber = orderEntity['JM_WORKORDERID'];
              orderData.materialNumber = orderEntity['MATCODE'];
              orderData.quantity = orderEntity['WOPLANQTY'];
              // orderData.serialNumber = orderEntity['WOSERIAL'];
              orderData.remark = orderEntity['WOCOMMENTS'];
              // 物料描述
              let matParam = `PM_MATERIAL🈹PM_MATERIALID🈹${orderEntity['MATCODE']}`;
              let matInfoList = await myAxios.get('陈帅廷查询大连通用数据', matParam);
              orderData.description = matInfoList[0]['MATNAME'];
              // BOM
              let wpnoObj = orderData.wpnoOptions.find(el => el['工序ID'] == orderData.wpno);
              let gx = wpnoObj['工序'];
              let bomParam = `${orderData.orderNumber}🈹${gx}`;
              let bomInfoList = await myAxios.get('陈帅廷查询大连订单BOM信息', bomParam);
              orderData.bomData = bomInfoList;
              orderData.bomDataZGJ = bomInfoList.filter(el => el['ZGJ'] == '0');

              orderData.collectionSerial = value;
              successMsg.value = '采集流水号: ' + value + ' 成功';
              inputText.value = '';
            }
            else {
              errorMsg.value = '未找到订单号:' + JM_WORKORDERID;
              return;
            }
          }
          else {
            errorMsg.value = '未找到流水号:' + value;
            return;
          }
        }
      }
      else {
        // errorMsg.value = '输入不能为空';
      }
    };
    const errorMsg = ref('');
    const successMsg = ref('');
    const nowDate = dayjs().format('YYYY/MM/DD');
    watch([errorMsg, successMsg], ([newError, newSuccess], [oldError, oldSuccess]) => {
      if (newError && newError != oldError) {
        if (!newError.startsWith(nowDate)) {
          errorMsg.value = dayjs().format('YYYY/MM/DD HH:mm:ss') + ' ' + newError;
        }
      }
      if (newSuccess && newSuccess != oldSuccess) {
        if (!newSuccess.startsWith(nowDate)) {
          successMsg.value = dayjs().format('YYYY/MM/DD HH:mm:ss') + ' ' + newSuccess;
        }
      }
      console.log('newError 新值:', newError, '旧值:', oldError);
      console.log('newSuccess 新值:', newSuccess, '旧值:', oldSuccess);
    });

    // 表单数据
    const orderData = reactive({
      orderNumber: '',
      materialNumber: '',
      quantity: 1,
      serialNumber: '',
      remark: '',

      wpno: 'gd0801',
      wpnoOptions: [],
      operator: [],
      collectionDate: dayjs().format('YYYY/MM/DD'),
      collectionSerial: '',
      activeTab: 'collected',
    });

    // 表格数据
    const collectedData = ref([
      {
        material: 'MCU-001',
        batch: 'B20250901',
        description: '主控芯片',
        supplier: '芯微电子',
        type: 'A型'
      },
      {
        material: 'PCB-002',
        batch: 'B20250902',
        description: '电路板',
        supplier: '华强科技',
        type: 'B型'
      },
      {
        material: 'SEN-003',
        batch: 'B20250903',
        description: '温度传感器',
        supplier: '感知科技',
        type: 'C型'
      }
    ]);

    const currentWorkData = ref([
      {
        serial: 'SN20250901001',
        description: '主控芯片采集',
        result: '成功',
        material: 'MCU-001',
        operator: '张三'
      },
      {
        serial: 'SN20250901002',
        description: '电路板检测',
        result: '成功',
        material: 'PCB-002',
        operator: '李四'
      },
      {
        serial: 'SN20250901003',
        description: '传感器校准',
        result: '失败',
        material: 'SEN-003',
        operator: '王五'
      }
    ]);

    const tableRowClassName = ({ rowIndex }) => {
      if (rowIndex % 2 === 0) {
        return 'success-row';
      } else {
        return 'warning-row';
      }
    };

    const deleteOperator = () => {
      operator.value = '';
      ElMessage.success('操作员信息已清除');
    };

    return {
      loading,
      buttonClick,
      orderData,

      inputText,
      handleInputChange,
      errorMsg,
      successMsg,

      collectedData,
      currentWorkData,

      tableRowClassName,
      deleteOperator,
    };
  }
}
</script>
<style lang="css" scoped>
.marginTop10 {
  margin-top: 10px;
}
/* .main-content {
  padding: 0 10px;
} */
</style>

